package cn.codesugar.jetpack

import android.content.Context
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.core.content.edit
import androidx.lifecycle.ViewModelProvider
import androidx.work.BackoffPolicy
import androidx.work.OneTimeWorkRequest
import androidx.work.WorkInfo
import androidx.work.WorkManager
import cn.codesugar.jetpack.database.AppDatabase
import cn.codesugar.jetpack.databinding.ActivityMainBinding
import cn.codesugar.jetpack.model.User
import cn.codesugar.jetpack.viewmodel.MainObserver
import cn.codesugar.jetpack.viewmodel.MainViewModel
import cn.codesugar.jetpack.viewmodel.MainViewModelFactory
import java.util.concurrent.TimeUnit
import kotlin.concurrent.thread

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private lateinit var viewModel: MainViewModel
    private lateinit var sp: SharedPreferences
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        lifecycle.let { it.addObserver(MainObserver(it)) }
        sp = getPreferences(Context.MODE_PRIVATE)
        val countReserved = sp.getInt("count_reserved", 0)
        viewModel = ViewModelProvider(this, MainViewModelFactory(countReserved)).get(MainViewModel::class.java)
        binding.plusOneBtn.setOnClickListener {
            viewModel.plusOne()
        }
        binding.clearBtn.setOnClickListener {
            viewModel.clear()
        }
        viewModel.counter.observe(this) {
            binding.infoText.text = it.toString()
        }
        binding.getUserBtn.setOnClickListener {
            val userId = (0..100000).random().toString()
            viewModel.getUser(userId)
        }
        viewModel.user.observe(this) {
            binding.infoText.text = it.firstName
        }
        binding.randomValueBtn.setOnClickListener {
            viewModel.refresh()
        }
        viewModel.refreshResult.observe(this) {
            binding.infoText.text = it.toString()
        }

        // Room功能
        val userDao = AppDatabase.getDatabase(this).userDao()
        val user1 = User("weDo", "tang", 18)
        val user2 = User("code", "sugar", 24)
        binding.addDataBtn.setOnClickListener {
            thread {
                user1.id = userDao.insertUser(user1)
                user2.id = userDao.insertUser(user2)
            }
        }
        binding.updateDataBtn.setOnClickListener {
            thread {
                user1.age = 15
                userDao.updateUser(user1)
            }
        }
        binding.deleteDataBtn.setOnClickListener {
            thread {
//                userDao.deleteUser(user1)
                userDao.deleteUserByLastName("tang")
            }
        }
        binding.queryDataBtn.setOnClickListener {
            thread {
                for (user in userDao.loadAllUsers()) {
                    Log.e("MainActivity", user.toString())
                }
            }
        }
        binding.doWorkBtn.setOnClickListener {
            val request = OneTimeWorkRequest.Builder(SimpleWorker::class.java)
                .setInitialDelay(5, TimeUnit.SECONDS)
                .addTag("simple")
                .setBackoffCriteria(BackoffPolicy.LINEAR, 10, TimeUnit.SECONDS)
                .build()
            val wm = WorkManager.getInstance(this)
            wm.enqueue(request)
//            wm.cancelAllWorkByTag("simple") // 可以取消该标签下所有的任务
//            wm.cancelWorkById(request.id) // 取消指定任务
//            wm.cancelAllWork() // 取消所有任务
            wm.getWorkInfoByIdLiveData(request.id)
                .observe(this) {
                    if (it.state == WorkInfo.State.SUCCEEDED) {
                        Log.e("MainActivity", "do work succeeded")
                    } else if (it.state == WorkInfo.State.FAILED) {
                        Log.e("MainActivity", "do work failed")
                    }
                }
//            val sync = ...
//            val compress = ...
//            val upload =
//            WorkManager.getInstance(this)
//                .beginWith(sync)
//                .then(compress)
//                .then(upload)
//                .enqueue()
        }
    }
    
    override fun onPause() {
        super.onPause()
        sp.edit {
            putInt("count_reserved", viewModel.counter.value ?: 0)
        }
    }
}